//
//  ViewController.m
//  myTel
//
//  Created by TMac on 17/9/4.
//  Copyright © 2017年 TMac. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate, UISearchBarDelegate>
{
    UITableView *tableView;
    NSMutableArray *tels;
    NSArray *backup;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    tels = [NSMutableArray new];
    [tels addObject:@"s,4534589"];
    [tels addObject:@"e,453445"];
    [tels addObject:@"t,453458"];
    [tels addObject:@"q,453485"];
    [tels addObject:@"d,453545"];
    [tels addObject:@"f,45345"];
    [tels addObject:@"g,433345"];
        backup = tels.copy;
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    [self.view addSubview:tableView];
    
    UISearchBar *bar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    bar.delegate = self;
    self.navigationItem.titleView = bar;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"%@",searchText);
    if (searchText.length == 0) {
        tels = backup.mutableCopy;
        return;
    }
    NSMutableArray *res = [NSMutableArray new];
    for (NSString *tel in backup) {
        if ([tel containsString:searchText]) {
            [res addObject:tel];
        }
    }
    tels = res;
    [tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return tels.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView_ cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView_ dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    NSString *tel = tels[indexPath.row];
    NSArray *tmp = [tel componentsSeparatedByString:@","];
    cell.textLabel.text = tmp.firstObject;
    cell.detailTextLabel.text = tmp.lastObject;
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
